//引入头文件
let url_js = require("../../utils/url.js");
let common_js = require("../../utils/common.js");
let const_js = require("../../utils/const.js");
let user_js = require("../../utils/user.js");
let sys_js = require("../../utils/system.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let cart_js = require("../../utils/cart.js");
let page_js = require("../../utils/pageOptions.js");
let wxp = require("../../utils/wxp.js");
let api = require("../../utils/apiRequest.js");
let util_js = require("../../utils/util.js");
let ws_js = require("../../utils/socket.js");
let notificationCenter = require('../../thridLib/WxNotificationCenter.js');

const app = getApp()
Page({
  data: {
    options: null, //onload所携带的参数
    shareShopInfo: null, //团长分享过来的shopInfo
    sysInfo: null,
    navBarHeight: 0,
    userInfo: null,
    canCusNav: true,
    pageScrollTop: 0,
    isDiscountShow: false,
    discountInfo: null,
    containerTouchmove: '',
    contentStatus: -1, //2已绑定门店
    header: {
      title: '好想你心选',
      headerbg: 'linear-gradient(#C7000B,#C74E51);',
      hiddenBack: true
    },
    limitTimerObj: { //限时抢购计时器对象
      timer: null,
      isEnd: false,
      endTime: '',
      item: null
    },
    bannerList: [], //轮播图
    cmsInfo: null, //cms广告
    ksAlertInfo: null, //开售提醒
    categoryInlineCWidth: 750,
    categoryList: [], //分类ƒ
    limitSaleList: [], //限时抢购list
    limitSaleInfo: {}, //首页限时抢购
    allGoodsCategoryList: [],
    allGoodsCategorySelectIndex: 0,
    allGoodsCategoryGoodsList: null, //根据省id存储县区数组,二维数组与map互换
    //当前选中的分类商品
    allGoodsCategorySelctedGoodsInfo: {
      pageInfo: {
        curPage: 1,
        pageSize: 10,
        noMore: false
      },
      itemList: []
    },
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    addCartSelctedGoodsInfo: null, //当前添加购物车的商品，只有当有多种规格时有数据,
    shareInfo: null, //分享信息
    isShareViewShow: false, //分享方式
    isPageShare: false, //海报
    pageShareImgUrl: null, //海报信息
    newUserInfo: null, //新用户信息
    millionGroupInfo: null, //新用户信息
    orderedInfo: null,//购买提醒
    hotKeyList: [], //搜索框内展示的数据
  },

  onLoad: function (options) {
    // 1.新版本强制更新
    common_js.checkUpdateVersion();
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.注册通知
    this.registNotification();
    if (options.scene) {
      this.initTzShopData(options);
      return;
    }

    //1.初始化数据
    this.initData(options);
    //2.选择角色
    this.chooseRoleToPlay();
    //3.处理
    if (user_js.hasRole()) {
      //3.2.网路请求获取数据
      this.getRemoteDatas(false);
      //4.ws
      this.initWebSocket();
    }
  },

  onReady() {
    this.setData({
      fixedContainer: () => this.createSelectorQuery().select('.container>.all-goods-category-c')
    })
  },

  // 初始化团长自提点----团长分享码进来
  initTzShopData(options) {
    if (!options) return;

    // 1.
    let scene = decodeURIComponent(options.scene);
    this.setData({
      options: options
    });

    //2.请求code
    if (!user_js.getCode()) {
      api.getAccessToken();
    } else {
      let tmpArr = scene.split(',');
      let shopId = tmpArr[0];
      //如果本地已经是当前自提点不提示切换
      let tempUserInfo = user_js.userInfo();
      if (tempUserInfo && tempUserInfo.ztd && tempUserInfo.ztd.id == shopId) {
        wx.reLaunch({
          url: '/pages/index/index'
        });
      } else {
        this.getShareShop(shopId);
      }
    }
  },

  // 获取团长信息
  getShareShop(shopId) {
    let data = {
      id: shopId
    }
    api.wxRequest(url_js.shopInfoUrl, data).then(res => {
      this.setData({
        shareShopInfo: res.result,
      });
      //提示用户是否选择团长的店铺
      wxp.showModal({
        title: '自提点切换',
        content: '是否切换至' + this.data.shareShopInfo.shopName + '?'
      }).then(res => {
        //选中当前自提点
        this.requestToSelectShop(this.data.shareShopInfo);
      }).catch(err => {
        //否 重新打开
        wx.reLaunch({
          url: '/pages/index/index'
        });
      });
    }).catch(err => {
      common_js.log(err);
    });
  },

  //选择自提点，将刚才的自提点信息返回
  requestToSelectShop: function (selectedItem) {
    let tmpSelectItem = selectedItem;
    let data = {
      code: user_js.getCode(),
      shopId: tmpSelectItem.id,
      geoLat: selectedItem.geoLat,
      geoLon: selectedItem.geoLon
    }
    api.wxRequest(url_js.shopSelectShopUrl, data).then(res => {
      this.handleSelectShopData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理选中自提点返回的数据
  handleSelectShopData: function (res) {
    //2.保存当前用户自提点
    let tempUserInfo = user_js.userInfo();
    //0 购物
    tempUserInfo.role = 1;
    tempUserInfo.ztd = this.data.shareShopInfo;
    user_js.saveUserInfo(tempUserInfo);
    wx.reLaunch({
      url: '/pages/index/index'
    });
  },

  // 获取用户位置
  getUserLocation() {
    if (user_js.hasRole()) return;
    if (this.data.options) return;

    // 获取设置
    wxp.getSetting().then(res => {
      // 位置设置
      if (!res.authSetting['scope.userLocation']) {
        // 提前授权用户位置信息
        this.authorizeUserLocation();
      } else {
        //授权过，判断是否有当前自提点，存在正常使用，否则，选择自提点
        if (user_js.hasRole() && this.data.contentStatus != 2) {
          //3.2.网路请求获取数据
          this.getRemoteDatas(true);
        } else {
          // 选择自提点
          wx.navigateTo({
            url: '/pages/indexSearchShop/indexSearchShop',
          })
        }
      }
    }).catch(err => {
      common_js.showToast("获取当前设置失败，请重试!");
    })
  },

  // 提前授权用户位置信息
  authorizeUserLocation() {
    wxp.authorize({
      scope: 'scope.userLocation'
    }).then(res => {
      // 选择自提点
      wx.navigateTo({
        url: '/pages/indexSearchShop/indexSearchShop',
      })
    }).catch(err => {
      //授权拒绝 
      let firstAuthDeny = err.errMsg.indexOf("fail auth deny") != -1;
      this.checkHasRole(firstAuthDeny);
    });
  },


  //注册通知，当自提点切换的时候，更新数据
  registNotification: function () {
    let that = this;
    notificationCenter.addNotification(const_js.changeShopSucessNoti, that.changedShop, that);
    notificationCenter.addNotification(const_js.getCodeSucessNoti, that.getCodeSuccess, that);
  },

  //微信获取code成功
  getCodeSuccess: function () {
    //3.初始化数据
    this.initTzShopData(this.data.options);
  },

  //自提点切换
  changedShop: function () {
    //1.更新userInfo
    let tempUserInfo = user_js.userInfo();
    this.setData({
      userInfo: tempUserInfo
    });
    //2.刷新数据
    this.getRemoteDatas(true);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //更新购物车数量，setTabBarBadge受限制
    cart_js.updateTabBarCount();
    //获取用户位置
    this.getUserLocation();
  },

  // 检查时候授权位置
  checkHasRole(firstAuthDeny) {
    if (firstAuthDeny) {
      this.goSelectZtPositionWithNoauther();
      return;
    }

    if (!user_js.hasRole()) {
      wxp.showModal({
        showCancel: false,
        content: '亲，我们未获得您的位置授权，即将打开设置'
      }).then(res => {
        this.goSelectZtPositionWithNoauther();
      }).catch(err => {
        common_js.log(err);
      });
    }
  },

  // 打开设定定位权限页面
  goSelectZtPositionWithNoauther() {
    // 打开设置页面
    let ztdObj = {};
    ztdObj.autherStatus = 0;
    wx.navigateTo({
      url: '/pages/selectZtPosition/selectZtPosition?ztdOjb=' + common_js.jsonStringify(ztdObj)
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //移除通知
    let that = this;
    notificationCenter.removeNotification(const_js.changeShopSucessNoti, that);
    notificationCenter.removeNotification(const_js.getCodeSucessNoti, that);

    //如果计时器的话清除
    if (this.data.limitTimerObj.timer) {
      clearTimeout(this.data.limitTimerObj.timer);
    }
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    this.setData({
      pageScrollTop: e.scrollTop
    });
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},

  //初始化数据
  initData: function (options) {
    //初始化购物车角标
    cart_js.initCartTabBarCount();
    //set data
    let navInfo = sys_js.navInfo();
    this.setData({
      canCusNav: app.globalData.canCusNav,
      sysInfo: sys_js.systemInfo(),
      navBarHeight: navInfo.statusBarHeight + navInfo.navBarHeight
    });

    //清除状态
    let tmpPageOptions = page_js.pageOptionsInfo();
    if (tmpPageOptions) {
      page_js.clearPageOptionsInfo();
    }
  },

  //计算类别的宽度
  updateCalculateCategoryWidth: function (categoryList) {
    //计算类别宽度
    let width = 750;
    if (categoryList.length > 8) {
      width += (Math.ceil((categoryList.length - 10) / 2) * 150);
      this.setData({
        categoryInlineCWidth: width,
      });
    }
  },

  //选择用户角色
  chooseRoleToPlay: function () {
    let tempUserInfo = user_js.userInfo();
    if (!tempUserInfo || tempUserInfo.role == -1) {

    } else {
      let tmpContentSt = this.data.contentStatus;
      if (tempUserInfo.ztd.shopName) {
        tmpContentSt = 2;
      }
      this.setData({
        contentStatus: tmpContentSt,
        userInfo: tempUserInfo
      });
    }
  },

  // 初始化ws
  initWebSocket() {
    let that = this;
    ws_js.webSocket.onSocketMillonMessage = function (res) {
      that.setData({
        millionGroupInfo: res.result
      })
    };
    ws_js.webSocket.onOrderedMessage = function (res) {
      that.setData({
        orderedInfo: res.result
      })
    }
  },

  //网络请求获取数据
  getRemoteDatas: function (pullDownRefresh) {

    //Promise.all
    let homeFlushSalesData = {
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      shopId: this.data.userInfo.ztd.id
    };
    let newUserData = {
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      shopId: this.data.userInfo.ztd.id
    }
    // 
    let shareData = {
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      shopId: this.data.userInfo.ztd.id,
      type: 0
    };
    //1.获取轮播图，分类，领券
    //2.获取限时抢购
    //3.获取首页分类
    //4.新用户专项
    //5.获取分享数据
    //6.滚动广告
    Promise.all([api.wxRequest(url_js.homeBannerIconUrl, {}), api.wxRequest(url_js.homeFlushSalesUrl, homeFlushSalesData), api.wxRequest(url_js.homeFrontCategoriesUrl, homeFlushSalesData), api.wxRequest(url_js.newUserActivityinfoUrl, newUserData), api.wxRequest(url_js.homeShareConfigUrl, shareData), api.wxRequest(url_js.groupJoinInfoUrl, newUserData), api.wxRequest(url_js.searchAdvertUrl, {})]).then(results => {
      this.resetAllData(pullDownRefresh);
      this.handleHomeBannerIconData(results[0]);
      this.handleHomeFlushSalesData(results[1]);
      this.handleHomeFrontCategoriesData(results[2]);
      this.handleNewUserData(results[3]);
      this.handleHomeShareConfigData(results[4]);
      this.handleMillionGroupInfo(results[5]);
      this.handleSearchAdvertData(results[6]);
      common_js.hidePageLoading(pullDownRefresh);
    }).catch(err => {
      common_js.hidePageLoading(pullDownRefresh);
      common_js.log(err);
    });
  },

  //重置数据
  //刷新重置数据
  resetAllData(pullDownRefresh) {
    if (!pullDownRefresh) return;

    let tmpBannerList = this.data.bannerList;
    tmpBannerList = [];

    let tmpCategoryList = this.data.categoryList;
    tmpCategoryList = [];

    let tmpLimitSaleList = this.data.limitSaleList;
    tmpLimitSaleList = [];

    let tmpAllGoodsCategoryList = this.data.allGoodsCategoryList;
    tmpAllGoodsCategoryList = [];

    let tmpAllGoodsCategoryGoodsList = this.data.allGoodsCategoryGoodsList;
    tmpAllGoodsCategoryGoodsList = [];

    //当前选中的分类商品
    let tmpAllGoodsCategorySelctedGoodsInfo = this.data.allGoodsCategorySelctedGoodsInfo;
    tmpAllGoodsCategorySelctedGoodsInfo.pageInfo.curPage = 1;
    tmpAllGoodsCategorySelctedGoodsInfo.pageInfo.pageSize = 10;
    tmpAllGoodsCategorySelctedGoodsInfo.pageInfo.noMore = false;
    tmpAllGoodsCategorySelctedGoodsInfo.itemList = [];

    let tmpTimer = this.data.limitTimerObj;
    tmpTimer.timer = null;
    tmpTimer.isEnd = false;
    tmpTimer.endTime = '';
    tmpTimer.item = null;

    this.setData({
      limitTimerObj: tmpTimer,
      bannerList: tmpBannerList,
      cmsInfo: null,
      categoryList: tmpCategoryList,
      limitSaleList: tmpLimitSaleList, //限时抢购list
      limitSaleInfo: {},
      allGoodsCategoryList: tmpAllGoodsCategoryList,
      allGoodsCategorySelectIndex: 0,
      categoryInlineCWidth: 750,
      allGoodsCategoryGoodsList: tmpAllGoodsCategoryGoodsList, //根据省id存储县区数组,二维数组与map互换
      allGoodsCategorySelctedGoodsInfo: tmpAllGoodsCategorySelctedGoodsInfo,
      addCartSelctedGoodsInfo: null
    });
  },

  //处理返回的轮播图数据
  handleHomeBannerIconData: function (res) {
    //轮播图
    let tmpBannerList = res.result.bannerVoList;
    //首页分类
    let tmpCateList = res.result.iconVoList;
    //cms活动
    let tmpCmsInfo = res.result.operateTilingVo;
    //开售提醒
    let tmpKsInfo = {
      waitTime: res.result.waitTime,
      next: res.result.next
    }
    //弹窗领券
    let tmpOperateAdvertVo = res.result.operateAdvertVo;
    this.setData({
      bannerList: tmpBannerList,
      categoryList: tmpCateList,
      cmsInfo: tmpCmsInfo,
      ksAlertInfo: tmpKsInfo
    });
    if (tmpOperateAdvertVo) {
      this.setData({
        discountInfo: tmpOperateAdvertVo,
        isDiscountShow: true,
        containerTouchmove: 'preventTouchMove'
      });
    }

    //跟新categoryList宽度
    this.updateCalculateCategoryWidth(tmpCateList);
  },

  //处理返回的轮播图数据
  handleHomeFlushSalesData: function (res) {
    if (!res.result || !res.result.productList) return;

    let tmpProList = res.result.productList;
    if (tmpProList.length == 0) return;
    //执行限时抢购倒计时
    let tmpLimitTimerObj = this.data.limitTimerObj;
    tmpLimitTimerObj.endTime = new Date().getTime() + res.result.expire * 1000;
    this.setData({
      limitTimerObj: tmpLimitTimerObj,
      limitSaleInfo: res.result,
      limitSaleList: tmpProList
    });
    //
    clearTimeout(this.data.limitTimerObj.timer);
    this.countDownLimitTimer();
  },

  //处理返回的分类数据
  handleHomeFrontCategoriesData: function (res) {
    let tmpCateList = res.result;
    if (tmpCateList.length > 0) {
      this.setData({
        allGoodsCategoryList: tmpCateList
      });
      //请求分类第一个商品数据
      let firstCateItem = tmpCateList[0];
      this.requestToGetHomeFrontCategoryProduct(firstCateItem.id, 1, 10);
    }
  },

  //处理返回的分享数据
  handleHomeShareConfigData: function (res) {
    this.setData({
      shareInfo: res.result
    });
  },

  //处理返回的新用户数据
  handleNewUserData(res) {
    let moveTxt = '';
    if (res.result && res.result.isOpen) {
      moveTxt = 'preventTouchMove';
    }
    this.setData({
      newUserInfo: res.result,
      containerTouchmove: moveTxt
    });
  },

  // 处理返回的万人团数据
  handleMillionGroupInfo(res) {
    this.setData({
      millionGroupInfo: res.result
    })
  },

  // 处理返回的关键词
  handleSearchAdvertData(res) {
    if (res.result && res.result.length > 0) {
      this.setData({
        hotKeyList: res.result
      })
    }
  },

  //首页分类对应的商品
  requestToGetHomeFrontCategoryProduct: function (categoryId, curPage, pageSize) {
    let data = {
      categoryId: categoryId,
      cityId: this.data.userInfo.ztd.cityId,
      code: this.data.userInfo.code,
      curPage: curPage,
      pageSize: pageSize,
      shopId: this.data.userInfo.ztd.id
    };
    api.wxRequest(url_js.homeFrontCategoryProductUrl, data).then(res => {
      this.handleHomeFrontCategoryProductData(res, curPage, categoryId);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理分类对应的商品
  handleHomeFrontCategoryProductData: function (res, curPage, categoryId) {
    let tmpGoodsMap = new Map(this.data.allGoodsCategoryGoodsList);
    let tmpGoodsInfo = null;
    if (tmpGoodsMap.get(categoryId)) {
      tmpGoodsInfo = tmpGoodsMap.get(categoryId);
    } else {
      tmpGoodsInfo = {
        pageInfo: {
          curPage: 1,
          pageSize: 10,
          noMore: false
        },
        itemList: []
      }
    }
    //page
    if (res.page.pages <= curPage) {
      tmpGoodsInfo.pageInfo.noMore = true;
    } else {
      tmpGoodsInfo.pageInfo.curPage++;
    }
    //list
    if (res.result.length > 0) {
      tmpGoodsInfo.itemList = tmpGoodsInfo.itemList.concat(res.result);
    }
    //set data
    tmpGoodsMap.set(categoryId, tmpGoodsInfo);
    this.setData({
      allGoodsCategorySelctedGoodsInfo: tmpGoodsInfo,
      allGoodsCategoryGoodsList: [...tmpGoodsMap]
    });
  },

  //增加购物车
  requestToAddCart: function (skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    common_js.showToast("添加购物车成功");
  },

  //新用户领券
  requestToCouponPick: function (couponPackageId) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      couponPackageId: couponPackageId,
      shopId: this.data.userInfo.ztd.id,
    };
    api.wxRequest(url_js.couponPickUrl, data).then(res => {
      this.handleCouponPickData(res);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理添加购物车
  handleCouponPickData: function (res) {
    common_js.showToast("领取成功");
    this.setData({
      discountInfo: null
    });
  },

  //选择自提点
  onPosition: function () {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexZtd);

    wx.navigateTo({
      url: '../indexSearchShop/indexSearchShop'
    })
  },
  //确定自提点
  ensurePosition: function () {

  },

  //点击banner
  onBanner: function (e) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexBanner);

    let index = e.currentTarget.dataset.index;
    let item = this.data.bannerList[index];
    //去掉头部的pages/
    let tmpLink = '../' + item.linkUrl;
    //跳转页面
    wx.navigateTo({
      url: tmpLink,
      fail: res => {
        common_js.showToast("跳转失败");
      }
    })
  },

  //点击cms占位图
  onCmsActivity: function () {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexCms);

    //去掉头部的pages/
    let tmpLink = '../' + this.data.cmsInfo.linkUrl;
    //跳转页面
    wx.navigateTo({
      url: tmpLink,
      fail: res => {
        common_js.showToast("跳转失败");
      }
    });
  },

  //点击类别
  onCategoryItem: function (e) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexCg);

    let index = e.currentTarget.dataset.index;
    let item = this.data.categoryList[index];
    if (item.linkType == 3) {
      wx.navigateTo({
        url: '../groupBuyingList/groupBuyingList'
      })
      return;
    }
    wx.navigateTo({
      url: '../goodsList/goodsList?item=' + common_js.jsonStringify(item)
    })
  },

  //搜索
  onSearch: function (e) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexSearch);

    wx.navigateTo({
      url: '../searchIndex/searchIndex'
    })
  },

  //更多限时抢购
  onLimitMore: function () {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexLimitMore);

    wx.navigateTo({
      url: '../hxnBuyLimit/index'
    });
  },

  //添加限时抢购商品
  onLimitAdd: function (e) {
    if (!this.checkIsToLoginIndex()) return;

    let index = e.currentTarget.dataset.index;
    let item = this.data.limitSaleList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexLimitGoodsAdd);
  },

  //查看限时商品详情
  onBuyLimitItem: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.limitSaleList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  },

  //查看商品详情
  onGoodsDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.allGoodsCategorySelctedGoodsInfo.itemList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    })
  },

  // 查看万人团商品详情
  onMillionBuyDetail() {
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + this.data.millionGroupInfo.productInfo.id
    })
  },

  //全部分类
  onAllGoodsCategery: function (e) {
    let index = e.currentTarget.dataset.index;
    if (this.data.allGoodsCategorySelectIndex == index) return;
    let item = this.data.allGoodsCategoryList[index];
    //判断是否已经存在
    let tmpGoodsMap = new Map(this.data.allGoodsCategoryGoodsList);
    let tmpGoodsSelectInfo = tmpGoodsMap.get(item.id);
    if (tmpGoodsSelectInfo) {
      this.setData({
        allGoodsCategorySelctedGoodsInfo: tmpGoodsSelectInfo,
        allGoodsCategorySelectIndex: index
      });
    } else {
      //请求当前分类下的商品
      this.requestToGetHomeFrontCategoryProduct(item.id, 1, 10);
      //set data
      this.setData({
        allGoodsCategorySelectIndex: index
      });
    }
  },

  //点击分类详情添加
  onAllCategoryGoodsAdd: function (e) {
    if (!this.checkIsToLoginIndex()) return;

    //2.加入购物车
    let index = e.currentTarget.dataset.index;
    let item = this.data.allGoodsCategorySelctedGoodsInfo.itemList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      //展示多规格商品
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexCategoryGoodsAdd);
  },

  //查看登录状态，未登录直接跳转登录
  checkIsToLoginIndex: function () {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return false;
    }
    return true;
  },

  //关闭领券弹窗
  onDiscountClose: function () {
    this.setData({
      isDiscountShow: false,
      containerTouchmove: ''
    });
  },

  // 关闭新人专项弹框
  onNewUserAlertClose() {
    let info = this.data.newUserInfo;
    info.isOpen = 0;
    this.setData({
      newUserInfo: info,
      containerTouchmove: ''
    });
  },

  //去领券
  onDiscount: function () {
    if (!this.checkIsToLoginIndex()) return;
    this.setData({
      isDiscountShow: false,
      containerTouchmove: '',
    });

    //判断类型
    if (this.data.discountInfo.linkType == 2) {
      //领券
      this.requestToCouponPick(this.data.discountInfo.linkParam);
    } else {
      //去掉头部的pages/
      let tmpLink = '../' + this.data.discountInfo.linkUrl;
      //跳转页面
      wx.navigateTo({
        url: tmpLink,
        fail: res => {
          common_js.showToast("跳转失败");
        }
      })
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.allGoodsCategorySelctedGoodsInfo.pageInfo.noMore) return;
    //1. request
    let item = this.data.allGoodsCategoryList[this.data.allGoodsCategorySelectIndex];
    if (item) {
      this.requestToGetHomeFrontCategoryProduct(item.id, this.data.allGoodsCategorySelctedGoodsInfo.pageInfo.curPage, this.data.allGoodsCategorySelctedGoodsInfo.pageInfo.pageSize);
    }
  },

  //商品属性选择确定
  onGoodsPropertyEnsure: function (e) {
    //消失
    this.onGoodsPropertyHidden();
    //添加购物车
    if (e) {
      let item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type != 0) {
        let skuItem = item.sku;
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  // 新人专享商品点击
  onNewUsrGoodsItem(e) {
    let item = e.detail.item;
    //跳转商品详情
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    });
  },

  // 新人专享详情页
  goNewUserDetail() {
    wx.navigateTo({
      url: '/pages/newUserGoodsList/index'
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.contentStatus != 2) {
      wx.stopPullDownRefresh();
      return
    }
    // //3.request
    this.getRemoteDatas(true);
  },

  // 点击首页分享按钮
  onShare() {
    this.setData({
      isShareViewShow: true,
      containerTouchmove: 'preventTouchMove'
    });
  },

  // 关闭分享
  onShareClose() {
    this.setData({
      isShareViewShow: false,
      containerTouchmove: ''
    });
  },

  // 微信分享
  onShareWechat() {
    this.onShareClose();
  },


  // 分享海报
  onShareHb() {
    this.getShopGenerate();

  },

  // 获取海报信息
  getShopGenerate() {
    let data = {
      id: this.data.userInfo.ztd.id,
      path: 'pages/index/index'
    }
    api.wxRequest(url_js.shopGenerateUrl, data).then(res => {
      this.setData({
        pageShareImgUrl: res.data
      })
      this.onShareClose();
      this.onPageShow();
    }).catch(err => {
      common_js.log(err);
    });
  },

  // 海报关闭
  onPageShow() {
    this.setData({
      isPageShare: true,
      containerTouchmove: 'preventTouchMove'
    });
  },

  // 海报关闭
  onPageClose() {
    this.setData({
      isPageShare: false,
      containerTouchmove: ''
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.indexShare);
    return this.shareAppMessage();
  },


  //获取分享的AppMessage
  shareAppMessage: function () {
    let userInfo = user_js.userInfo();
    let tmpPath = '/pages/index/index?scene=' + userInfo.ztd.id
    return {
      title: this.data.shareInfo ? this.data.shareInfo.title : '好想你心选',
      path: tmpPath,
      imageUrl: this.data.shareInfo ? this.data.shareInfo.href : ''
    }
  },

  // 限时抢购计时器**********
  countDownLimitTimer() { //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let tmpTimerObj = this.data.limitTimerObj;
    let endTime = tmpTimerObj.endTime;
    let time = (endTime - newTime) / 1000;
    // 如果活动未结束，对时间进行处理
    let hmsObj = common_js.getHrMinSecBySecond(time);
    tmpTimerObj.item = hmsObj.item;
    tmpTimerObj.isEnd = hmsObj.isEnd;
    //1s调用一次
    let that = this;
    let timerItem = setTimeout(function () {
      that.countDownLimitTimer()
    }, 1000);
    //定时清除
    clearTimeout(this.data.limitTimerObj.timer);
    if (tmpTimerObj.isEnd) {
      clearTimeout(timerItem);
      return;
    } else {
      tmpTimerObj.timer = timerItem;
    }
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({
      limitTimerObj: tmpTimerObj
    })
  }
  // 限时抢购计时器**********
})